#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 17:02
import time
from typing import List

from domain.report.common.period_enum import PeriodEnum
from infrastructure.common.threadingPool import ThreadPool
from domain.report.dto.profit_dto import ProfitDTO, ProfitSchema
from infrastructure.util.selenium_spider import RequestMethodEnum, SeleniumSpider2JsonConfiguration, spider2json


"""
https://xueqiu.com/snowman/S/SH600050/detail#/GSLRB
财务报表接口：https://stock.xueqiu.com/v5/stock/finance/cn/income.json?symbol=SH600050&type=Q4&is_detail=true&count=5&timestamp=
"""



@ThreadPool(thread_name_prefix="xueqiu_")
def _balance_sheet_spider(stock_code:str, period:PeriodEnum=None, count:int=5):
    arr = stock_code.split(".")
    stock_code = f"{arr[1]}{arr[0]}"
    url = f"""
        https://stock.xueqiu.com/v5/stock/finance/cn/income.json?symbol={stock_code}
        &type={"all" if period is None else f"Q{period.value}"}
        &is_detail=true&count={count}&timestamp={time.time()}
    """
    configuration = SeleniumSpider2JsonConfiguration()
    configuration.add_prepose_url(f"https://xueqiu.com/snowman/S/{stock_code}/detail#/GSLRB", method=RequestMethodEnum.get)
    configuration.set_data_url(url)
    result = spider2json(configuration)
    return result


_xueqiuPeriod2_localPeriod = {
    "一季报": PeriodEnum.first_quarter,
    "中报": PeriodEnum.half_year,
    "三季报": PeriodEnum.three_quarter,
    "年报": PeriodEnum.year
}


def _spider_assembler(data:dict, stock_code, period: PeriodEnum) -> List[ProfitDTO]:
    """
    未定位元素：exchg_gain
    """
    dto_list = list()
    if data and len(data) > 0 and data.get("data", None) and data["data"].get("list", None):
        data_list = data["data"]["list"]
        for item in data_list:
            dto = ProfitDTO()
            dto.stock_code = stock_code
            dto.stock_id = stock_code.split(".")[0]
            dto.year = int(item["report_name"][:3])
            dto.period = _xueqiuPeriod2_localPeriod[item["report_name"][4:]]
            ProfitSchema.set(dto, "asset_disposal_income", item["asset_disposal_income"])
            ProfitSchema.set(dto, "assets_impair_loss", item["asset_impairment_loss"])
            ProfitSchema.set(dto, "basic_eps", item["basic_eps"])
            ProfitSchema.set(dto, "continous_operating_np", item["continous_operating_np"])
            ProfitSchema.set(dto, "credit_impairment_loss", item["credit_impairment_loss"])
            ProfitSchema.set(dto, "diluted_eps", item["dlt_earnings_per_share"])
            ProfitSchema.set(dto, "finance_cost_interest_fee", item["finance_cost_interest_fee"])
            ProfitSchema.set(dto, "finance_cost_interest_income", item["finance_cost_interest_income"])
            ProfitSchema.set(dto, "financing_expenses", item["financing_expenses"])
            ProfitSchema.set(dto, "fv_value_chg_gain", item["income_from_chg_in_fv"])
            ProfitSchema.set(dto, "income_tax", item["income_tax_expenses"])
            ProfitSchema.set(dto, "invest_income", item["invest_income"])
            ProfitSchema.set(dto, "invest_incomes_from_rr", item["invest_incomes_from_rr"])
            ProfitSchema.set(dto, "manage_fee", item["manage_fee"])
            ProfitSchema.set(dto, "minority_gain", item["minority_gal"])
            ProfitSchema.set(dto, "net_profit", item["net_profit"])
            ProfitSchema.set(dto, "net_profit_after_nrgal_atsolc", item["net_profit_after_nrgal_atsolc"])
            ProfitSchema.set(dto, "net_profit_to_p_corp", item["net_profit_atsopc"])
            ProfitSchema.set(dto, "net_profit_bi", item["net_profit_bi"])
            ProfitSchema.set(dto, "non_operating_income", item["non_operating_income"])
            ProfitSchema.set(dto, "non_operating_payout", item["non_operating_payout"])
            ProfitSchema.set(dto, "noncurrent_asset_disposal_loss", item["noncurrent_asset_disposal_loss"])
            ProfitSchema.set(dto, "noncurrent_assets_dispose_gain", item["noncurrent_assets_dispose_gain"])
            ProfitSchema.set(dto, "noncurrent_assets_dispose_remain", dto.noncurrent_asset_disposal_loss + dto.noncurrent_assets_dispose_gain)
            ProfitSchema.set(dto, "operate_profit", item["op"])
            ProfitSchema.set(dto, "operating_cost", item["operating_cost"])
            ProfitSchema.set(dto, "total_operating_cost", item["operating_costs"])
            ProfitSchema.set(dto, "operating_taxes_and_surcharge", item["operating_taxes_and_surcharge"])
            ProfitSchema.set(dto, "other_income", item["other_income"])
            ProfitSchema.set(dto, "other_comprehensive_income", item["othr_compre_income"])
            ProfitSchema.set(dto, "other_comprehensive_income_to_p_corp", item["othr_compre_income_atoopc"])
            ProfitSchema.set(dto, "total_profit", item["profit_total_amt"])
            ProfitSchema.set(dto, "dev_cost", item["rad_cost"])
            ProfitSchema.set(dto, "revenue", item["revenue"])
            ProfitSchema.set(dto, "sales_fee", item["sales_fee"])
            ProfitSchema.set(dto, "total_comprehensive_income", item["total_compre_income"])
            ProfitSchema.set(dto, "total_comprehensive_income_to_minority", item["total_compre_income_atms"])
            ProfitSchema.set(dto, "total_comprehensive_income_to_p_corp", item["total_compre_income_atsopc"])
            ProfitSchema.set(dto, "total_revenue", item["total_revenue"])
    return dto_list

def spider(stock_code:str, period:PeriodEnum=None, count:int=5) -> List[ProfitDTO]:
    result = _balance_sheet_spider(stock_code, period, count)
    dtos = None
    if result and len(result) > 0:
        dtos = _spider_assembler(result, stock_code, period)
    return dtos